package com.atguigu.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Set;

/**
 * className: ChatServer
 * description: 服务器端
 * date: 2023/3/10 0010-16:07
 * <p>
 * project: nio
 * package: com.atguigu.server
 * email: 1085844536@qq.com
 * version:
 *
 * @author WangGuojian
 */
public class ChatServer {

    /**
     * 服务器端启动的方法
     */
    public void startServer() throws IOException {
        // 1.创建 Selector 选择器
        Selector selector = Selector.open();

        // 2.创建 ServerSocketChannel 通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        // 3.为 channel 通道绑定监听端口
        serverSocketChannel.bind(new InetSocketAddress(8000));
        // 设置非阻塞模式
        serverSocketChannel.configureBlocking(false);

        // 4.把 channel 通道注册到 selector 选择器上
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println("服务器已经启动成功了");

        // 5.循环，等待有新的连接接入
        for (; ; ) {
            // 获取 channel 数量
            int readChannels = selector.select();

            if (readChannels == 0) {
                continue;
            }

            // 获取可用的 channel
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            // 遍历集合
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();

                // 移除 set 集合当前 selectionKey
                iterator.remove();

                // 6.根据就绪状态，调用对应方法实现具体业务操作
                // 6.1如果 accept 状态
                if (selectionKey.isAcceptable()) {
                    acceptOperator(serverSocketChannel, selector);
                }
                // 6.2如果可读状态
                if (selectionKey.isReadable()) {
                    readOperator(selector, selectionKey);
                }
            }
        }
    }

    /**
     * 处理可读状态操作
     *
     * @param selector     {@link Selector}
     * @param selectionKey {@link SelectionKey}
     */
    private void readOperator(Selector selector, SelectionKey selectionKey) throws IOException {
        // 1.从 SelectionKey 获取到已经就绪的通道
        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();

        // 2.创建 buffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

        // 3.循环读取客户端消息
        int readLength = socketChannel.read(byteBuffer);
        StringBuilder message = new StringBuilder();
        if (readLength > 0) {
            // 切换模式
            byteBuffer.flip();

            // 读取内容
            message.append(StandardCharsets.UTF_8.decode(byteBuffer));
        }

        // 4.将channel 再次注册到选择器上，监听可读状态
        socketChannel.register(selector, SelectionKey.OP_READ);

        // 5.把客户端发送消息，广播到其他客户端
        if (message.toString().length() > 0) {
            // 广播给其他客户端
            System.out.println(message);
            castOtherClient(message.toString(), selector, socketChannel);
        }
    }

    /**
     * 广播到其他客户端
     *
     * @param message       {@link String} 消息
     * @param selector      {@link Selector} 选择器
     * @param socketChannel {@link SocketChannel} 源 socketChannel
     */
    private void castOtherClient(String message, Selector selector, SocketChannel socketChannel) throws IOException {
        // 1.获取到所有已经接入 channel
        Set<SelectionKey> keys = selector.keys();

        // 2.循环向所有 channel 广播消息
        for (SelectionKey selectionKey : keys) {
            // 获取每个 channel
            Channel targetChannel = selectionKey.channel();
            // 不需要给自己发送
            if (targetChannel instanceof SocketChannel && targetChannel != socketChannel) {
                ((SocketChannel) targetChannel).write(StandardCharsets.UTF_8.encode(message));
            }
        }
    }

    /**
     * 处理接入状态操作
     *
     * @param serverSocketChannel {@link  ServerSocketChannel}
     * @param selector            {@link  Selector}
     */
    private void acceptOperator(ServerSocketChannel serverSocketChannel, Selector selector) throws IOException {
        // 1.接入状态，创建 socketChannel
        SocketChannel socketChannel = serverSocketChannel.accept();

        // 2.把 socketChannel 设置非阻塞模式
        socketChannel.configureBlocking(false);

        // 3.把 channel 注册到选择器上，监听可读状态
        socketChannel.register(selector, SelectionKey.OP_READ);

        // 4.客户端回复信息
        socketChannel.write(StandardCharsets.UTF_8.encode("欢迎进入聊天室，请注意隐私安全"));
    }

    /**
     * 启动主方法
     *
     * @param args {@link String[]}
     */
    public static void main(String[] args) {
        try {
            new ChatServer().startServer();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
